<?php

class SubfolderAccessManager_Acl extends Zend_Acl
{
	private $_noAuth;
	private $_noAcl;

	public function __construct()
	{
		$config = Zend_Registry::get('config');
		$roles = $config->acl->roles;
		$resources = $config->acl->resources;
		$this->_addRoles($roles);
		$this->_addResources($resources);
		$this->_loadRedirectionActions($config->acl);
	}

	public function setNoAuthAction($noAuth)
	{
		$this->_noAuth = $noAuth;
	}

	public function setNoAclAction($noAcl)
	{
		$this->_noAcl = $noAcl;
	}
	public function getNoAuthAction()
	{
		return $this->_noAuth;
	}

	public function getNoAclAction()
	{
		return $this->_noAcl;
	}

	protected function _addRoles($roles)
	{
		foreach ($roles as $name => $parents) {
			if (!$this->hasRole($name)) {
				if (empty($parents)) {
					$parents = null;
				} else {
					$parents = explode(',', $parents);
				}
				$this->addRole(new Zend_Acl_Role($name), $parents);
			}
		}
	}

	protected function _addResources($resources) {

		foreach ($resources as $permissions => $controllers) {

			foreach ($controllers as $controller => $actions) {
				if ($controller == 'all') {
					$controller = null;
				} else {
					if (!$this->has($controller)) {
						$this->add(new Zend_Acl_Resource($controller));
					}
				}

				foreach ($actions as $action => $role) {
					if ($action == 'all') {
						$action = null;
					}
					if ($permissions == 'allow') {
						$this->allow($role, $controller, $action);
					}
					if ($permissions == 'deny') {
						$this->deny($role, $controller, $action);
					}
				}
			}
		}
	}

	protected function _loadRedirectionActions($aclConfig)
	{
		$this->_noAuth = array('module' => 'default',
				'controller' => 'auth',
				'action' => 'form');

		$this->_noAcl = array('module' => 'default',
				'controller' => 'auth',
				'action' => 'privileges');
	}
}
